#include <graphics/mesh.h>
#include <graphics/vertexbuffer.h>
#include <graphics/indexbuffer.h>
#include <graphics/camera.h>
#include <QGLShaderProgram>
#include <graphics/utils.h>

namespace yam3d
{
namespace graphics
{

Mesh::Mesh(VertexBuffer* vb, IndexBuffer* ib)
    : core::Object(__FUNCTION__)
    , m_vb(vb)
    , m_ib(ib)
{
    assert(vb != 0);
    assert(ib != 0);
}

Mesh::~Mesh()
{
}

VertexBuffer* Mesh::getVertexBuffer() const
{
    assert(m_vb != 0);
    return m_vb.ptr();
}

IndexBuffer* Mesh::getIndexBuffer() const
{
    assert(m_ib != 0);
    return m_ib.ptr();
}


void Mesh::getTriangles(TriangleListType* triangles) const
{
    core::vector<math::vec3> positions;
    getVertexBuffer()->getVertexArray("a_position")->getData(&positions);
    core::vector<unsigned int> indices;
    getIndexBuffer()->getIndices(&indices);

    assert( (indices.size()%3) == 0 );
    triangles->resize( indices.size()/3 );
    for( int i=0; i<indices.size(); i+=3 )
    {
        (*triangles)[i/3].v1 = positions[ indices[i+0] ];
        (*triangles)[i/3].v2 = positions[ indices[i+1] ];
        (*triangles)[i/3].v3 = positions[ indices[i+2] ];
    }
}

/*
void Mesh::renderGeometryWithShader(QGLShaderProgram* program, Camera* camera )
{
    // Set uniform values for matrices
    math::mat4 matModel = getTransform();
    math::mat4 matView = camera->getView();
    math::mat4 matProj = camera->getProjection();
    math::mat4 matWorldView = matView.inverted();
    math::mat4 matModelView = matWorldView * matModel;
    math::mat4 matModelViewInverseTranspose = matModelView.inverted().transposed();
    math::mat4 matModelViewProj = matProj * matModelView;

    program->setUniformValue("vecEyePositionWorld", camera->getTranslation() );

    program->setUniformValue("matModel", matModel );
    program->setUniformValue("matView", matView );
    program->setUniformValue("matProj", matProj );
    program->setUniformValue("matWorldView", matWorldView );
    program->setUniformValue("matModelView", matModelView );
    program->setUniformValue("matModelViewInverseTranspose", matModelViewInverseTranspose );
    program->setUniformValue("matModelViewProj", matModelViewProj );

    getVertexBuffer()->setVertexArrays(program);
    getIndexBuffer()->draw();
}*/

Light::Light()
 : core::Object(__FUNCTION__)
{
}

Light::~Light()
{
}

}
}

